package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ExtensionUtilKt;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerRentSeekingListComponent;
import com.kmproject.haifu.mvp.contract.RentSeekingListContract;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.RentSeekingDetail;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsQueryHoseRentSeekingList;
import com.kmproject.haifu.mvp.presenter.RentSeekingListPresenter;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.adapter.SelectRegionAdapter2;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.ExpandableTextView;
import com.kmproject.haifu.mvp.ui.widget.MyTextWatcher;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.xw.repo.XEditText;
import com.yyydjk.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.luliang.shapeutils.DevShapeUtils.getContext;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/12/2019 17:51
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class RentSeekingListActivity extends BaseActivity<RentSeekingListPresenter> implements RentSeekingListContract.View, TextView.OnEditorActionListener, View.OnKeyListener {
    @BindView(R.id.ll_top_search_layout)
    LinearLayout ll_top_search_layout;
    @BindView(R.id.include_title_search_xedit)
    XEditText include_title_search_xedit;
    @BindView(R.id.include_title_search_msg)
    ImageView include_title_search_msg;
    @BindView(R.id.include_title_search_back)
    ImageView include_title_search_back;
    @BindView(R.id.ddm_layout)
    DropDownMenu ddm_layout;

    private List<View> popupViews = new ArrayList<>();
    private String headers[];
    private String mKeyWord;
    private ReqParamsQueryHoseRentSeekingList reqParamsQueryHoseRentSeekingList;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRentSeekingListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_rent_seeking_list; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @OnClick({R.id.include_title_search_back, R.id.include_title_search_msg, R.id.include_title_search_xedit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_title_search_back: {
                killMyself();
            }
            break;
            case R.id.include_title_search_msg: {
                AppUtil.gotoMessage(this);
            }
            break;
            case R.id.include_title_search_xedit: {
                showSearchHistoryView();
            }
            break;
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        reqParamsQueryHoseRentSeekingList = new ReqParamsQueryHoseRentSeekingList();
        reqParamsQueryHoseRentSeekingList.setPage(1);
        reqParamsQueryHoseRentSeekingList.setLimit(AppConstant.pageSize);

        if (AppUtil.userIsLogin(this)) {
            userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
//            assert userBean != null;
//            reqParamsQueryHoseRentSeekingList.setUserId(Long.parseLong(userBean.getUserId()));
        }
        initPopupViews();
        include_title_search_xedit.setHint(getString(R.string.rent_seeking_list_search_hint));
        include_title_search_xedit.setFocusable(false);

        assert mPresenter != null;
        showLoading();
        sentSearch();
        mPresenter.getHouseArea(areaList);
        mPresenter.getPrice(priceList);
        mPresenter.getReleaseType(typeList);
    }

    private View locationView;
    private View rentingView;
    private View typeView;
    private View searchHistoryView;
    private View contentView;

    private void initPopupViews() {
        headers = getResources().getStringArray(R.array.rent_seeking_menu_text);

        initLocationView();
        initRentingView();
        initRentSeekingTypeView();
        initContentView();

        popupViews.add(locationView);
        popupViews.add(rentingView);
        popupViews.add(typeView);

        ddm_layout.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
    }

    private PullToRefreshView srl_rent_seeking;
    private RecyclerView rv_rent_seeking;
    private BaseRecyclerAdapter<RentSeekingDetail> adapter;
    private UserBean userBean;//获取用户信息
    private View empty;

    private void initContentView() {
        if (contentView == null) {
            contentView = LayoutInflater.from(this).inflate(R.layout.v_rent_seeking_list, null);
            srl_rent_seeking = contentView.findViewById(R.id.srl_rent_seeking);
            rv_rent_seeking = contentView.findViewById(R.id.rv_rent_seeking);
            empty = contentView.findViewById(R.id.i_empty);

            rv_rent_seeking.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).
                    setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.color_line_D8D8D8)).setShowLastLine(false).build());
            ArmsUtils.configRecyclerView(rv_rent_seeking, new LinearLayoutManager(getContext()));
            rv_rent_seeking.setItemAnimator(new DefaultItemAnimator());

            adapter = new BaseRecyclerAdapter<RentSeekingDetail>(R.layout.item_rent_seeking) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, RentSeekingDetail model, int position) {
                    String category = model.getSeekingType();
                    StringBuilder sb = new StringBuilder();
                    if (!StringUtils.isEmpty(category)) {
                        switch (category) {
                            case "zz":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(model.getRoomCountName()).append(model.getDrawingCountName()).append(model.getToiletCountName());
                                break;
                            case "hz":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(ExtensionUtilKt.appendAcreage(RentSeekingListActivity.this, model.getLowestAcreage(), model.getHighestAcreage()));
                                break;
                            case "bs":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(model.getRoomCountName()).append(model.getDrawingCountName()).append(model.getToiletCountName());
                                break;
                            case "bgs":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(ExtensionUtilKt.appendAcreage(RentSeekingListActivity.this, model.getLowestAcreage(), model.getHighestAcreage()));
                                break;
                            case "sp":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(ExtensionUtilKt.appendAcreage(RentSeekingListActivity.this, model.getLowestAcreage(), model.getHighestAcreage()));
                                break;
                            case "cw":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()));
                                break;
                            case "cfck":
                                sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                        .append(" | ")
                                        .append(ExtensionUtilKt.appendAcreage(RentSeekingListActivity.this, model.getLowestAcreage(), model.getHighestAcreage()));
                                break;
                        }
                    }
                    holder.text(R.id.tv_rent_seeking_base_info, sb);
                    StringBuilder sbPrice = new StringBuilder();
                    sbPrice.append(model.getLowestRentBudget()).append("-").append(model.getHighestRentBudget()).append(String.format(getString(R.string.rent_seeking_detail_fm_4), handUnit(model.getTenancy(), model.getEstimateRentingUnitName())));
                    holder.text(R.id.tv_price, sbPrice);
                    TextView tv_detail_desc = (TextView) holder.findViewById(R.id.tv_detail_desc);
                    tv_detail_desc.setMaxLines(2);
                    tv_detail_desc.setText(model.getDetailDesc());
                    StringBuilder sbAddress = new StringBuilder();
                    sbAddress.append(model.getParentSeekingAreaName()).append(model.getSeekingAreaName()).append(model.getPositionDescription());
                    holder.text(R.id.tv_address, sbAddress);
                    RelativeLayout rl_bottom_layout = (RelativeLayout) holder.findViewById(R.id.rl_bottom_layout);
                    TextView tv_release_time = (TextView) holder.findViewById(R.id.tv_release_time);
                    TextView tv_release_time_2 = (TextView) holder.findViewById(R.id.tv_release_time_2);
                    tv_release_time.setText(String.format(getString(R.string.rent_seeking_detail_fm_5), model.getLatestTime()));
                    tv_release_time_2.setText(String.format(getString(R.string.rent_seeking_detail_fm_5), model.getLatestTime()));

                    RecyclerView rvRequirement = (RecyclerView) holder.findViewById(R.id.rv_house_requirement);
                    if (model.getHouseRentDetailList() != null && model.getHouseRentDetailList().size() > 0) {
                        rvRequirement.setVisibility(View.VISIBLE);
                        rvRequirement.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(20f).
                                setHorizontalSpan(15f).setColor(ContextCompat.getColor(getContext(), R.color.white)).setShowLastLine(false).build());
                        ArmsUtils.configRecyclerView(rvRequirement, new GridLayoutManager(RentSeekingListActivity.this, 4));
                        rvRequirement.setItemAnimator(new DefaultItemAnimator());

                        rvRequirement.setAdapter(new BaseRecyclerAdapter<RentSeekingDetail.HouseRentDetailListBean>(model.getHouseRentDetailList(), R.layout.item_release_room_feature) {
                            @Override
                            protected void onBindViewHolder(SmartViewHolder holder, RentSeekingDetail.HouseRentDetailListBean model, int position) {
                                RoundTextView textView = (RoundTextView) holder.findViewById(R.id.rtv_unique_feature);
                                textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
                                textView.getDelegate().setStrokeWidth(1);
                                textView.getDelegate().setStrokeColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
//                                textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
                                textView.setText(model.getBaseDictName());
                            }
                        });
                    } else {
                        rvRequirement.setVisibility(View.GONE);
                    }
                    LinearLayout ll_bottom_operation = (LinearLayout) holder.findViewById(R.id.ll_bottom_operation);
                    RoundTextView rtv_edit = (RoundTextView) holder.findViewById(R.id.rtv_edit);
                    RoundTextView rtv_delete = (RoundTextView) holder.findViewById(R.id.rtv_delete);
//                    if (userBean != null && userBean.getUserId().equals(String.valueOf(model.getUserId()))) {
//                        tv_release_time.setVisibility(View.GONE);
//                        rl_bottom_layout.setVisibility(View.VISIBLE);
//                        tv_release_time_2.setVisibility(View.VISIBLE);
//                        ll_bottom_operation.setVisibility(View.VISIBLE);
//                        rtv_edit.setOnClickListener(v -> {
//                            Intent intent = new Intent(RentSeekingListActivity.this, ReleaseRentSeekingActivity.class);
//                            intent.putExtra("seekingId", String.valueOf(model.getSeekingId()));
//                            ArmsUtils.startActivity(intent);
//                        });
//                        rtv_delete.setTag(position);
//                        rtv_delete.setOnClickListener(v -> {
//                            int tag = (int) v.getTag();
//                            new AlertView(getString(R.string.note), getString(R.string.rent_seeking_delete_pmt), getString(R.string.cancel), new String[]{getString(R.string.sure_delete)}, null, RentSeekingListActivity.this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {
//
//                                @Override
//                                public void onItemClick(Object o, int position) {
//                                    if (position != AlertView.CANCELPOSITION) {
//                                        assert mPresenter != null;
//                                        mPresenter.delete(String.valueOf(((RentSeekingDetail) adapter.getItem(tag)).getSeekingId()));
//                                    }
//                                }
//                            }).show();
//                        });
//                    } else {
//                        tv_release_time.setVisibility(View.VISIBLE);
//                        rl_bottom_layout.setVisibility(View.GONE);
//                        ll_bottom_operation.setVisibility(View.GONE);
//                        tv_release_time_2.setVisibility(View.GONE);
//                    }
                    tv_release_time.setVisibility(View.VISIBLE);
                    rl_bottom_layout.setVisibility(View.GONE);
                    ll_bottom_operation.setVisibility(View.GONE);
                    tv_release_time_2.setVisibility(View.GONE);
                }
            };
            rv_rent_seeking.setAdapter(adapter);

            adapter.setOnItemClickListener((parent, view, position, id) -> {
                Intent intent = new Intent(RentSeekingListActivity.this, RentSeekingDetailActivity.class);
                intent.putExtra("seekingId", String.valueOf(((RentSeekingDetail) adapter.getItem(position)).getSeekingId()));
                ArmsUtils.startActivity(intent);
            });

            srl_rent_seeking.setEnableRefresh(true);
            srl_rent_seeking.setEnableAutoLoadMore(false);
            srl_rent_seeking.setEnableHeaderTranslationContent(true);

            srl_rent_seeking.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                    reqParamsQueryHoseRentSeekingList.setPage(curPageNo);
                    sentSearch();
                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                    reqParamsQueryHoseRentSeekingList.setPage(curPageNo);
                    sentSearch();
                }
            });
        }
    }

    private String handUnit(String tenancy, String oldUnit) {
        if (tenancy.equals("short")) {//租期要求:short-短租，lasting-长租
            return getString(R.string.day_t);
        }
        return oldUnit;
    }

    private RecyclerView popupWindowsSelectAddressRv_1;
    private RecyclerView popupWindowsSelectAddressRv_2;
    private RecyclerView popupWindowsSelectAddressRv_3;
    private View v_split_line_1;
    private View v_split_line_2;
    private SelectRegionAdapter2 mSelectRegionAdapter1;
    private SelectRegionAdapter2 mSelectRegionAdapter2;
    private SelectRegionAdapter2 mSelectRegionAdapter3;
    private List<HousePayWayBean> areaList = new ArrayList<>();

    private void initLocationView() {
        if (locationView == null) {
            locationView = LayoutInflater.from(this).inflate(R.layout.popuwindows_select_address, null);
            popupWindowsSelectAddressRv_1 = locationView.findViewById(R.id.popup_windows_select_address_rv_1);
            popupWindowsSelectAddressRv_2 = locationView.findViewById(R.id.popup_windows_select_address_rv_2);
            popupWindowsSelectAddressRv_3 = locationView.findViewById(R.id.popup_windows_select_address_rv_3);
            v_split_line_1 = locationView.findViewById(R.id.v_split_line_1);
            v_split_line_2 = locationView.findViewById(R.id.v_split_line_2);

            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

            ArmsUtils.configRecyclerView(popupWindowsSelectAddressRv_1, layoutManager);
            ArmsUtils.configRecyclerView(popupWindowsSelectAddressRv_2, new LinearLayoutManager(this));
            ArmsUtils.configRecyclerView(popupWindowsSelectAddressRv_3, new LinearLayoutManager(this));

            mSelectRegionAdapter1 = new SelectRegionAdapter2(AppConstant.houseArea);
            mSelectRegionAdapter2 = new SelectRegionAdapter2(new ArrayList<>());
            mSelectRegionAdapter3 = new SelectRegionAdapter2(new ArrayList<>());

            popupWindowsSelectAddressRv_1.setAdapter(mSelectRegionAdapter1);
            popupWindowsSelectAddressRv_2.setAdapter(mSelectRegionAdapter2);
            popupWindowsSelectAddressRv_3.setAdapter(mSelectRegionAdapter3);
            mSelectRegionAdapter1.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
            mSelectRegionAdapter2.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
            mSelectRegionAdapter3.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);

            mSelectRegionAdapter1.setOnItemClickListener((adapter, view, position) -> {
                if (mSelectRegionAdapter1.getData().get(position).getChildren() != null && mSelectRegionAdapter1.getData().get(position).getChildren().size() > 0) {
                    v_split_line_1.setVisibility(View.VISIBLE);
                    popupWindowsSelectAddressRv_2.setVisibility(View.VISIBLE);

                    List<HousePayWayBean> tempList = new ArrayList<>();
//                    HousePayWayBean unLimitBean = new HousePayWayBean();
//                    unLimitBean.setName(getString(R.string.un_limit));
//                    unLimitBean.setDictId("-1");
//                    tempList.add(unLimitBean);
                    tempList.addAll(mSelectRegionAdapter1.getData().get(position).getChildren());

                    mSelectRegionAdapter2.setNewData(tempList);
                    popupWindowsSelectAddressRv_2.smoothScrollToPosition(0);
                } else {
                    HousePayWayBean housePayWayBean = mSelectRegionAdapter1.getData().get(position);
                    ddm_layout.closeMenu();
                    if (housePayWayBean.getDictId().equals("-1")) {
                        reqParamsQueryHoseRentSeekingList.setSeekingArea(null);
                    } else {
                        reqParamsQueryHoseRentSeekingList.setSeekingArea(housePayWayBean.getDictId());
                    }
                    reqParamsQueryHoseRentSeekingList.setPage(1);
                    sentSearch();
                }
            });
            mSelectRegionAdapter2.setOnItemClickListener((adapter, view, position) -> {
                if (mSelectRegionAdapter2.getData().get(position).getChildren() != null && mSelectRegionAdapter2.getData().get(position).getChildren().size() > 0) {
                    v_split_line_2.setVisibility(View.VISIBLE);
                    popupWindowsSelectAddressRv_3.setVisibility(View.VISIBLE);

                    List<HousePayWayBean> tempList = new ArrayList<>();
//                    HousePayWayBean unLimitBean = new HousePayWayBean();
//                    unLimitBean.setName(getString(R.string.un_limit));
//                    unLimitBean.setDictId("-1");
//                    tempList.add(unLimitBean);
                    tempList.addAll(mSelectRegionAdapter2.getData().get(position).getChildren());

                    mSelectRegionAdapter3.setNewData(tempList);
                    popupWindowsSelectAddressRv_3.smoothScrollToPosition(0);
                } else {
                    HousePayWayBean housePayWayBean = mSelectRegionAdapter2.getData().get(position);
                    ddm_layout.closeMenu();
                    if (housePayWayBean.getDictId().equals("-1")) {
                        reqParamsQueryHoseRentSeekingList.setSeekingArea(null);
                    } else {
                        reqParamsQueryHoseRentSeekingList.setSeekingArea(housePayWayBean.getDictId());
                    }
                    reqParamsQueryHoseRentSeekingList.setPage(1);
                    sentSearch();
                }
            });
            mSelectRegionAdapter3.setOnItemClickListener((adapter, view, position) -> {
                HousePayWayBean housePayWayBean = mSelectRegionAdapter3.getData().get(position);
                ddm_layout.closeMenu();
                if (housePayWayBean.getDictId().equals("-1")) {
                    reqParamsQueryHoseRentSeekingList.setSeekingArea(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setSeekingArea(housePayWayBean.getDictId());
                }
                reqParamsQueryHoseRentSeekingList.setPage(1);
                sentSearch();
            });
        }
    }

    private RecyclerView rv_rent_seeking_renting;
    private EditText et_rent_seeking_low_price;
    private EditText et_rent_seeking_height_price;
    private TextView tv_rent_seeking_bottom_operation;
    private List<HousePayWayBean> priceList = new ArrayList<>();
    private BaseRecyclerAdapter<HousePayWayBean> priceAdapter;

    private void initRentingView() {
        if (rentingView == null) {
            rentingView = LayoutInflater.from(this).inflate(R.layout.v_rent_seeking_renting, null);
            rv_rent_seeking_renting = rentingView.findViewById(R.id.rv_rent_seeking_renting);
            et_rent_seeking_low_price = rentingView.findViewById(R.id.et_rent_seeking_low_price);
            et_rent_seeking_height_price = rentingView.findViewById(R.id.et_rent_seeking_height_price);
            tv_rent_seeking_bottom_operation = rentingView.findViewById(R.id.tv_rent_seeking_bottom_operation);

            rv_rent_seeking_renting.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(20f).
                    setHorizontalSpan(10f).setColor(ContextCompat.getColor(getContext(), R.color.white)).setShowLastLine(false).build());
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ArmsUtils.configRecyclerView(rv_rent_seeking_renting, layoutManager);
            rv_rent_seeking_renting.setItemAnimator(new DefaultItemAnimator());

            priceAdapter = new BaseRecyclerAdapter<HousePayWayBean>(R.layout.item_release_room_feature) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, HousePayWayBean model, int position) {
                    RoundTextView textView = (RoundTextView) holder.findViewById(R.id.rtv_unique_feature);
                    textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
                    textView.getDelegate().setStrokeColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
                    textView.setText(model.getName());
                }
            }.setOnItemClickListener((parent, view, position, id) -> {
                int[] r = ExtensionUtilKt.handlePrice(((HousePayWayBean) priceAdapter.getItem(position)).getName(), RentSeekingListActivity.this);
                if (r[0] == 0) {
                    reqParamsQueryHoseRentSeekingList.setLowestRentBudget(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setLowestRentBudget(String.valueOf(r[0]));
                }
                if (r[1] == 0) {
                    reqParamsQueryHoseRentSeekingList.setHighestRentBudget(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setHighestRentBudget(String.valueOf(r[1]));
                }
                reqParamsQueryHoseRentSeekingList.setPage(1);
                sentSearch();
                ddm_layout.closeMenu();
            });

            rv_rent_seeking_renting.setAdapter(priceAdapter);

            tv_rent_seeking_bottom_operation.setOnClickListener(v -> {
                String lowPrice = et_rent_seeking_low_price.getText().toString();
                String heightPrice = et_rent_seeking_height_price.getText().toString();
                if (StringUtils.isEmpty(lowPrice)) {
                    selectPmt2(et_rent_seeking_low_price.getHint().toString());
                    return;
                }
                if (StringUtils.isEmpty(heightPrice)) {
                    selectPmt2(et_rent_seeking_height_price.getHint().toString());
                    return;
                }
                if (Long.parseLong(lowPrice) >= Long.parseLong(heightPrice)) {
                    selectPmt2(getString(R.string.release_rent_seeking_pmt_3));
                    return;
                }

                if (lowPrice.equals("0")) {
                    reqParamsQueryHoseRentSeekingList.setLowestRentBudget(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setLowestRentBudget(lowPrice);
                }
                if (heightPrice.equals("0")) {
                    reqParamsQueryHoseRentSeekingList.setHighestRentBudget(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setHighestRentBudget(heightPrice);
                }
                reqParamsQueryHoseRentSeekingList.setPage(1);
                sentSearch();
                ddm_layout.closeMenu();
            });
        }
    }

    private RecyclerView rv_rent_seeking_type;
    private RoundTextView rtv_rent_seeking_require_short;
    private RoundTextView rtv_rent_seeking_require_long;
    private TextView tv_clear;
    private TextView tv_sure;
    private int selectedPosition = -1;
    private String selectedRequire;// 租期要求
    private List<HousePayWayBean> typeList = new ArrayList<>();
    private BaseRecyclerAdapter<HousePayWayBean> typeAdapter;

    private void initRentSeekingTypeView() {
        if (typeView == null) {
            typeView = LayoutInflater.from(this).inflate(R.layout.v_rent_seeking_type, null);
            rv_rent_seeking_type = typeView.findViewById(R.id.rv_rent_seeking_type);
            rtv_rent_seeking_require_short = typeView.findViewById(R.id.rtv_rent_seeking_require_short);
            rtv_rent_seeking_require_long = typeView.findViewById(R.id.rtv_rent_seeking_require_long);
            tv_clear = typeView.findViewById(R.id.tv_clear);
            tv_sure = typeView.findViewById(R.id.tv_sure);

            rv_rent_seeking_type.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(40f).
                    setHorizontalSpan(40f).setColor(ContextCompat.getColor(getContext(), R.color.white)).setShowLastLine(false).build());
            ArmsUtils.configRecyclerView(rv_rent_seeking_type, new GridLayoutManager(this, 4));
            rv_rent_seeking_type.setItemAnimator(new DefaultItemAnimator());

            typeAdapter = new BaseRecyclerAdapter<HousePayWayBean>(R.layout.item_release_room_feature_1) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, HousePayWayBean model, int position) {
                    RoundTextView textView = (RoundTextView) holder.findViewById(R.id.rtv_unique_feature);
                    if (selectedPosition == position) {
                        textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
                        textView.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.common_title_text));
                    } else {
                        textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_AAAAAA));
                        textView.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
                    }
                    textView.setText(model.getName());
                }
            }.setOnItemClickListener((parent, view, position, id) -> {
                selectedPosition = position;
                Objects.requireNonNull(rv_rent_seeking_type.getAdapter()).notifyDataSetChanged();
                ((BaseRecyclerAdapter) rv_rent_seeking_type.getAdapter()).notifyListDataSetChanged();
            });

            rv_rent_seeking_type.setAdapter(typeAdapter);
            rtv_rent_seeking_require_short.setOnClickListener(v -> {
                selectedRequire = "short";
                rtv_rent_seeking_require_short.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
                rtv_rent_seeking_require_short.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.common_title_text));
                rtv_rent_seeking_require_long.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_AAAAAA));
                rtv_rent_seeking_require_long.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
            });
            rtv_rent_seeking_require_long.setOnClickListener(v -> {
                selectedRequire = "lasting";
                rtv_rent_seeking_require_long.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
                rtv_rent_seeking_require_long.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.common_title_text));
                rtv_rent_seeking_require_short.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_AAAAAA));
                rtv_rent_seeking_require_short.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
            });
            tv_clear.setOnClickListener(v -> {
                selectedPosition = -1;
                selectedRequire = null;
                typeAdapter.notifyDataSetChanged();
                typeAdapter.notifyListDataSetChanged();
                rtv_rent_seeking_require_short.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_AAAAAA));
                rtv_rent_seeking_require_short.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));
                rtv_rent_seeking_require_long.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_AAAAAA));
                rtv_rent_seeking_require_long.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.white));

                // todo  是否需要发起查询，待定，目前暂时开放
                ddm_layout.closeMenu();
                reqParamsQueryHoseRentSeekingList.setTenancy(null);
                reqParamsQueryHoseRentSeekingList.setSeekingType(null);
                reqParamsQueryHoseRentSeekingList.setPage(1);
                sentSearch();
            });
            tv_sure.setOnClickListener(v -> {
                if (selectedPosition == -1 && StringUtils.isTrimEmpty(selectedRequire)) {
                    showMessage("请选择条件");
                    return;
                }
                ddm_layout.closeMenu();
                reqParamsQueryHoseRentSeekingList.setTenancy(selectedRequire);
                if (selectedPosition == -1) {
                    reqParamsQueryHoseRentSeekingList.setSeekingType(null);
                } else {
                    reqParamsQueryHoseRentSeekingList.setSeekingType(((HousePayWayBean) typeAdapter.getItem(selectedPosition)).getDictId());
                }
                reqParamsQueryHoseRentSeekingList.setPage(1);
                sentSearch();
            });
        }
    }

    private CustomPopWindow mCustomPopWindow4SearchHistory;
    private XEditText et_keyword;
    private TextView tv_clear_all;
    private TextView tv_cancel;
    private RecyclerView rv_rent_seeking_search_history;
    private BaseRecyclerAdapter<String> searchHistoryAdapter;

    private void showSearchHistoryView() {
        if (mCustomPopWindow4SearchHistory == null) {
            searchHistoryView = LayoutInflater.from(this).inflate(R.layout.v_rent_seeking_search_history, null);
            rv_rent_seeking_search_history = searchHistoryView.findViewById(R.id.rv_rent_seeking_search_history);
            et_keyword = searchHistoryView.findViewById(R.id.et_keyword);
            tv_clear_all = searchHistoryView.findViewById(R.id.tv_clear_all);
            tv_cancel = searchHistoryView.findViewById(R.id.tv_cancel);
            rv_rent_seeking_search_history.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                    setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(false).build());
            ArmsUtils.configRecyclerView(rv_rent_seeking_search_history, new LinearLayoutManager(getContext()));
            rv_rent_seeking_search_history.setItemAnimator(new DefaultItemAnimator());

            searchHistoryAdapter = new BaseRecyclerAdapter<String>(R.layout.item_rent_seeking_search_history) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, String model, int position) {
                    holder.text(R.id.tv_record_text, model);
                }
            }.setOnItemClickListener((parent, view, position, id) -> {
                mKeyWord = (String) searchHistoryAdapter.getItem(searchHistoryAdapter.getRealItemPosition(position));
                dismissHistoryPw();
            });

            rv_rent_seeking_search_history.setAdapter(searchHistoryAdapter);
            tv_clear_all.setOnClickListener(v -> {
                clearSearchHistory();
                showMessage(getString(R.string.success));
            });
            tv_cancel.setOnClickListener(v -> {
                if (StringUtils.isEmpty(et_keyword.getTextEx())) {
                    mKeyWord = "";
                } else {
                    mKeyWord = et_keyword.getTextEx();
                    addSearchHistory(mKeyWord);
                }
                KeyboardUtils.hideSoftInput(this);
                dismissHistoryPw();
            });
            et_keyword.setOnEditorActionListener(this);
            et_keyword.setOnKeyListener(this);
            et_keyword.addTextChangedListener(new MyTextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                    if (StringUtils.isEmpty(s)) {
                        mKeyWord = "";
                        tv_cancel.setText(getString(R.string.cancel));
                        tv_cancel.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_191919));
                    } else {
                        mKeyWord = et_keyword.getTextEx();
                        tv_cancel.setText(getString(R.string.search));
                        tv_cancel.setTextColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.textColor_alert_button_others));
                    }
                }
            });

            mCustomPopWindow4SearchHistory = initDropDownMenu(searchHistoryView, ViewGroup.LayoutParams.MATCH_PARENT);
        } else {
            mCustomPopWindow4SearchHistory.showAsDropDown(ll_top_search_layout, 0, 0);
        }
        getSearchHistory();
    }

    private CustomPopWindow initDropDownMenu(View contentView, int height) {
        ViewGroup parentViewGroup = (ViewGroup) contentView.getParent();
        if (parentViewGroup != null) {
            parentViewGroup.removeAllViews();
        }
        //创建并显示popWindow
        CustomPopWindow mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, height)
                .setAnimationStyle(R.style.popupWindowAnimationScale)
                .enableBackgroundDark(false) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .create();
        mCustomPopWindow.getPopupWindow().setOnDismissListener(() -> {
            if (StringUtils.isEmpty(mKeyWord)) {
                include_title_search_xedit.setTextEx("");
            } else {
                include_title_search_xedit.setTextEx(mKeyWord);
            }
        });
        mCustomPopWindow.showAsDropDown(ll_top_search_layout, 0, 0);

//        vHalfWhiteLayout.setVisibility(View.VISIBLE);
        return mCustomPopWindow;
    }

    private void selectPmt2(String msg) {
        showMessage(String.format(getString(R.string.release_rent_seeking_pmt_fm_2), msg));
    }

    private List<String> searchHistory;

    private void getSearchHistory() {
        if (searchHistory == null) {
            searchHistory = new ArrayList<>();
        }
        List<String> sh = DataHelper.getDeviceData(this, AppConstant.RENT_SEEKING_SEARCH_HISTORY);
        if (sh != null) {
            searchHistory.clear();
            searchHistory.addAll(sh);
        }
        searchHistoryAdapter.refresh(searchHistory);
    }

    private void addSearchHistory(String searchKey) {
        searchHistoryAdapter.add(searchKey);
        searchHistory.add(0, searchKey);
        DataHelper.saveDeviceData(this, AppConstant.RENT_SEEKING_SEARCH_HISTORY, searchHistory);
    }

    private void clearSearchHistory() {
        searchHistory.clear();
        searchHistoryAdapter.refresh(searchHistory);
        DataHelper.removeSF(this, AppConstant.RENT_SEEKING_SEARCH_HISTORY);
        searchHistory = null;
    }

    @Override
    public void getHouseArea(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null) {
            areaList.clear();
            HousePayWayBean unLimitBean = new HousePayWayBean();
            unLimitBean.setName(getString(R.string.un_limit));
            unLimitBean.setDictId("-1");
            areaList.add(unLimitBean);

            areaList.addAll(housePayWayBeans);
            mSelectRegionAdapter1.setNewData(areaList);
        }
    }

    @Override
    public void getReleaseTypeSuccess(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null) {
            typeList.clear();

            typeList.addAll(housePayWayBeans);
            typeAdapter.refresh(typeList);
        }
    }

    @Override
    public void getPriceSuccess(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null) {
            priceList.clear();
            HousePayWayBean unLimitBean = new HousePayWayBean();
            unLimitBean.setName(getString(R.string.un_limit));
            priceList.add(unLimitBean);

            priceList.addAll(housePayWayBeans);
            priceAdapter.refresh(priceList);
        }
    }

    @Override
    public void getRentSeekingListSuccess(List<RentSeekingDetail> housePayWayBeans) {
        srl_rent_seeking.finishLoadMore();
        srl_rent_seeking.finishRefresh();
        if (housePayWayBeans != null && !housePayWayBeans.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_rent_seeking, true);
            if (ViewExtensionKt.isPullDown(srl_rent_seeking, housePayWayBeans.size(), reqParamsQueryHoseRentSeekingList.getLimit())) {
                adapter.refresh(housePayWayBeans);
            } else {
                adapter.loadMore(housePayWayBeans);
            }
        } else {
            if (reqParamsQueryHoseRentSeekingList.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_rent_seeking, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_rent_seeking, false);
            }
        }
    }

    @Override
    public void getListFailed() {
        srl_rent_seeking.finishLoadMore();
        srl_rent_seeking.finishRefresh();
        if (reqParamsQueryHoseRentSeekingList.getPage() > 1) {
            reqParamsQueryHoseRentSeekingList.setPage(reqParamsQueryHoseRentSeekingList.getPage() - 1);
        }
    }

    @Override
    public void deleteSuccess() {
        sentSearch();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onBackPressed() {
        //退出activity前关闭菜单
        if (ddm_layout.isShowing()) {
            ddm_layout.closeMenu();
        } else {
            super.onBackPressed();
        }
    }

    private void sentSearch() {
        assert mPresenter != null;
        mPresenter.getRentSeekingList(reqParamsQueryHoseRentSeekingList);
    }

    private void dismissHistoryPw() {
        if (mCustomPopWindow4SearchHistory != null) {
            mCustomPopWindow4SearchHistory.dissmiss();
        }
        reqParamsQueryHoseRentSeekingList.setPage(1);
        if (!StringUtils.isTrimEmpty(mKeyWord)) {
            reqParamsQueryHoseRentSeekingList.setKeywords(mKeyWord);
            sentSearch();
        } else {
            mKeyWord = "";
            reqParamsQueryHoseRentSeekingList.setKeywords("");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mCustomPopWindow4SearchHistory != null) {
                mCustomPopWindow4SearchHistory.dissmiss();
            } else {
                exitCurrentPage();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出当前界面
     */
    private void exitCurrentPage() {
        KeyboardUtils.hideSoftInput(this);
        onBackPressed();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // 搜索
            if (!StringUtils.isTrimEmpty(mKeyWord)) {
                KeyboardUtils.hideSoftInput(this);
                addSearchHistory(mKeyWord);
                dismissHistoryPw();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
            case EditorInfo.IME_ACTION_DONE:
            case EditorInfo.IME_ACTION_GO:
            case EditorInfo.IME_ACTION_NEXT:
            case EditorInfo.IME_ACTION_SEND: {
                // 搜索
                if (!StringUtils.isTrimEmpty(mKeyWord)) {
                    KeyboardUtils.hideSoftInput(this);
                    addSearchHistory(mKeyWord);
                    dismissHistoryPw();
                }
                return true;
            }
        }
        return false;
    }
}
